package wang.chunfan;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.*;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

public class User implements BeanNameAware, BeanFactoryAware,
        ApplicationContextAware, InitializingBean, DisposableBean {
    private String userName;
    private int step;

    public String getUserName() {
        return userName;
    }

    // 1. 实例化时调用无参构造函数
    public User() {
        step++;
        System.out.println(step + "：调用构造函数 User()");
    }

    //2. 使用 Setter 方式注入属性
    public void setUserName(String userName) {
        step++;
        System.out.println(step + "：注入属性 userName = " + userName);
        this.userName = userName;
    }

    //3. 实现 BeanNameAware，获取 beanId
    public void setBeanName(String s) {
        step++;
        System.out.println(step + "：调用 setBeanName() 获取 beanId = " + s);
    }

    // 4. 实现 BeanFactoryAware，获取 bean 工厂
    public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
        step++;
        System.out.println(step + "：调用 setBeanFactory() 获取 bean 工厂，beanFactory=" + beanFactory);
    }

    // 5. 实现 ApplicationContextAware，获取 ApplicationContext bean 上下文
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        step++;
        System.out.println(step + "：调用 setApplicationContext() 获取 bean 上下文，applicationContext = " + applicationContext);
    }

    // 6. 实现 InitializingBean， 调用 afterPropertiesSet()
    public void afterPropertiesSet() throws Exception {
        step++;
        System.out.println(step + "：实现，InitializingBean 调用 afterPropertiesSet()");
    }

    // 7. 自定义初始化方法 myInit()
    public void myInit() {
        step++;
        System.out.println(step + "：配置 init-method，调用自定义 myInit()");
    }

    // 8.实现 DisposableBean，调用 destroy()
    public void destroy() throws Exception {
        step++;
        System.out.println(step + "：调用 destroy()");
    }

    // 9. 自定义销毁方法 myDestroy()
    public void myDestroy() {
        step++;
        System.out.println(step + "：调用自定义 destroy()");
    }


}
